package com.uinnova.product.eam.service.asset.impl;

import com.alibaba.fastjson.JSON;
import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.comm.model.es.AppPanoramaInfo;
import com.uinnova.product.eam.comm.model.es.EamDiagramRelationSys;
import com.uinnova.product.eam.model.asset.AppSystemBaseInfoConfig;
import com.uinnova.product.eam.model.asset.AppSystemInfoResponse;
import com.uinnova.product.eam.model.asset.AppSystemStructureInfo;
import com.uinnova.product.eam.service.AppPanoramaSvc;
import com.uinnova.product.eam.service.asset.AppSystemDetailSvc;
import com.uinnova.product.eam.service.asset.AppSystemSvc;
import com.uinnova.product.eam.service.asset.BmConfigSvc;
import com.uinnova.product.eam.service.es.EamDiagramRelationSysDao;
import com.uinnova.product.vmdb.comm.model.ci.CcCiAttrDef;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uinnova.project.api.diagram.v2.client.ESDiagramApiClient;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uino.dao.cmdb.ESCIClassSvc;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AppSystemDetailSvcImpl implements AppSystemDetailSvc {
    @Value("${http.resource.space}")
    private String httpResourceUrl;
    @Autowired
    private AppSystemSvc appSystemSvc;
    @Resource
    private ESCIClassSvc classSvc;
    @Resource
    private BmConfigSvc bmConfigSvc;
    @Resource
    private EamDiagramRelationSysDao relationSysDao;
    @Resource
    private ESDiagramApiClient diagramApiClient;

    @Resource
    AppPanoramaSvc appPanoramaSvc;

    @Override
    public AppSystemInfoResponse queryAppSystemInfo(String ciCode) {
        AppSystemInfoResponse result = new AppSystemInfoResponse();
        CcCiInfo ciInfo = appSystemSvc.queryAppSystemByCode(ciCode);
        if(ciInfo == null){
            return result;
        }
        //暂做处理
        String systemBaseConfig = bmConfigSvc.getConfigType("SYSTEM_BASE_INFO");
        AppSystemBaseInfoConfig config = JSON.parseObject(systemBaseConfig, AppSystemBaseInfoConfig.class);
        Map<String, String> attrs = ciInfo.getAttrs();
        result.setCiCode(ciCode);
        result.setTitle(attrs.get(config.getTitle()));
        //logo取值调整：取CI里的属性值
        String icon = attrs.get(config.getIcon().toUpperCase());
        if(BinaryUtils.isEmpty(icon)){
            //取一下该字段默认图
            icon = ciInfo.getAttrDefs().stream().filter(each -> each.getProName().equals(config.getIcon())).map(CcCiAttrDef::getDefVal).findFirst().orElse(null);
        }
        if (icon != null && !icon.startsWith(httpResourceUrl)) {
            icon = httpResourceUrl + icon;
        }
        result.setIcon(icon);
        for (String key : config.getOne()) {
            Map<String, String> oneMap = new HashMap<>();
            oneMap.put("name", key);
            oneMap.put("value", attrs.getOrDefault(key, ""));
            result.getOneRow().add(oneMap);
        }
        for (String each : config.getTwo()) {
            result.getTwoRow().add(attrs.getOrDefault(each, ""));
        }
        result.setThreeRow(attrs.get(config.getThree()));
        List<AppSystemStructureInfo> body = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : config.getBody().entrySet()) {
            AppSystemStructureInfo structureInfo = new AppSystemStructureInfo(entry.getKey());
            for (String each : entry.getValue()) {
                Map<String, String> field = new HashMap<>();
                field.put("name", each);
                field.put("value", attrs.get(each));
                structureInfo.getBody().add(field);
            }
            body.add(structureInfo);
        }
        result.setBody(body);
        return result;
    }

    @Override
    public List<Map<String, String>> getSystemArchitectureDiagram(String ciCode) {
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(QueryBuilders.termQuery("esSysId.keyword", ciCode));
        query.must(QueryBuilders.termQuery("delFlag", false));
        List<EamDiagramRelationSys> list = relationSysDao.getListByQuery(query);
        List<Map<String, String>> result = new ArrayList<>();
       List<String> allDiagramId = new ArrayList<>();
        List<String> diagramIds = list.stream().map(EamDiagramRelationSys::getDiagramEnergy).filter(Objects::nonNull).collect(Collectors.toList());
        allDiagramId.addAll(diagramIds);
        // 查询配置关联关息
        AppPanoramaInfo panoramaInfo = appPanoramaSvc.getPanoramaInfoByCiCode(ciCode);
        if (!BinaryUtils.isEmpty(panoramaInfo)) {
            List<String> relevanceDiagramIds = panoramaInfo.getDiagramIds();
            allDiagramId.addAll(relevanceDiagramIds);
        }
        allDiagramId = allDiagramId.stream().filter(e -> !BinaryUtils.isEmpty(e)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(allDiagramId)) {
            return result;
        }
        List<ESDiagram> diagramList = diagramApiClient.selectByIds(allDiagramId, null, null);
        Map<String, String> diagramIdMap = diagramList.stream().filter(esDiagram -> !BinaryUtils.isEmpty(esDiagram.getReleaseDiagramId()))
                .collect(Collectors.toMap(esDiagram -> esDiagram.getReleaseDiagramId(), esDiagram -> esDiagram.getDEnergy(), (k1, k2) -> k1));
        List<String> releaseDiagram = diagramList.stream().map(ESDiagram::getReleaseDiagramId).filter(Objects::nonNull).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(releaseDiagram)){
            return result;
        }
        List<ESDiagram> releaseDiagramList = diagramApiClient.selectByIds(releaseDiagram, null, Collections.singletonList(1));
        if(CollectionUtils.isEmpty(releaseDiagramList)){
            return result;
        }
        for (ESDiagram each : releaseDiagramList) {
            Map<String, String> map = new HashMap<>();
            map.put("id", each.getDEnergy());
            map.put("name", each.getName());
            map.put("viewType", each.getViewType());
            // 区分是否关联类型
            String privateDiagramId = diagramIdMap.get(each.getDEnergy());
            if (!BinaryUtils.isEmpty(privateDiagramId) && diagramIds.contains(privateDiagramId)) {
                map.put("relevancy", "1");
            } else {
                map.put("relevancy", "2");
            }
            result.add(map);
        }
        return result;
    }
}
